﻿using System;
using System.Data;
using System.Collections.Specialized;
using System.Collections.Generic;
using Com.Alipay;

/// <summary>
/// 功能：页面跳转同步通知页面
/// 版本：3.3
/// 日期：2012-07-10
/// 说明： 
/// 
/// ///////////////////////页面功能说明///////////////////////
/// 该页面可在本机电脑测试
/// 可放入HTML等美化页面的代码、商户业务逻辑程序代码
/// 该页面可以使用ASP.NET开发工具调试，也可以使用写文本函数LogResult进行调试
/// </summary>
public partial class mreturn_url : msBsc.Cls.mbPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Request.QueryString.Get("score_pay") == "1")
        //{
        //    ShowPayInfo();
        //    return;
        //}

        //if (Request.QueryString.Get("do_pay") == "1")
        //{
        //    ShowPayInfo();
        //    return;
        //}

        string out_trade_no = Request.QueryString.Get("out_trade_no");
        string strAlipayInfo = "";
        SortedDictionary<string, string> sPara = GetRequestGet();

        if (sPara.Count > 0 && !string.IsNullOrEmpty(Request.QueryString["notify_id"]) && !string.IsNullOrEmpty(Request.QueryString["sign"]))//判断是否有带返回参数
        {
            Notify aliNotify = new Notify();
            bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

            if (verifyResult)//验证成功
            {
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //请在这里加上商户的业务逻辑程序代码


                //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

                //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
                string trade_no = Request.Params["trade_no"];         //支付宝交易号
                string order_no = Request.Params["out_trade_no"];     //获取订单号
                string total_fee = Request.Params["price"];           //获取总金额
                string subject = Request.Params["subject"];           //商品名称、订单名称
                string body = Request.Params["body"];                 //商品描述、订单备注、描述
                string buyer_email = Request.Params["buyer_email"];   //买家支付宝账号
                string trade_status = Request.Params["trade_status"]; //交易状态
                string refund_status = Request.Params["refund_status"];//退款状态

                out_trade_no = order_no;


                ////商户订单号

                //out_trade_no = Request.QueryString["out_trade_no"];

                ////支付宝交易号

                //string trade_no = Request.QueryString["trade_no"];

                ////交易状态
                //string trade_status = Request.QueryString["trade_status"];
            //http://www.yousogou.com/Alipay/return_url.aspx?buyer_email=anfur99%40163.com&buyer_id=2088212401071088&exterface=create_direct_pay_by_user&is_success=T&notify_id=RqPnCoPT3K9%252Fvwbh3InQ%252Fmbk75OJgN4eM5jYUdhkKK%252Btbye9AAgEMaLsDEBDRMRTObkv&notify_time=2014-12-19+11%3A20%3A45&notify_type=trade_status_sync&out_trade_no=5429603326850100590&payment_type=1&seller_email=3024939353%40qq.com&seller_id=2088511831699252&subject=%D4%DA%CF%DF%B3%E4%D6%B5&total_fee=0.01&trade_no=2014121935968008&trade_status=TRADE_SUCCESS&sign=3bd326cc3605e2ce979618e547acb687&sign_type=MD5

                if (trade_status == "TRADE_FINISHED" || trade_status == "TRADE_SUCCESS")
                {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序

                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpChargeTradingLog objtradlog = new msBsc.AppLogic.DataAlc.CBizShpChargeTradingLog())
                        {
                            strAlipayInfo = objtradlog.doSaveAlipay(trade_no, order_no, total_fee, subject, body, buyer_email, trade_status, refund_status);
                        }
                        ts.Complete();
                    }

                }
                else
                {
                    strAlipayInfo = "未成功支付：交易状态=" + trade_status;
                    //Response.Write("trade_status=" + trade_status);
                }

                //打印页面
                //Response.Write("验证成功<br />");

                //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }
            else//验证失败
            {
                strAlipayInfo = "支付宝返回参数验证失败";
                //Response.Write("验证失败");
            }
        }
        //else
        //{
        //strAlipayInfo = "无返回参数";
        //Response.Write("无返回参数");
        //}
        ShowPayInfo(out_trade_no, strAlipayInfo);
    }

    public string strInfoTitle = "";
    public string strOrderNo = "";
    public string strOrderNme = "";
    public string strPaylist = "";
    public string strPayVali = "";
    private void ShowPayInfo(string order_no, string strAlipayInfo)
    {
        if (order_no == string.Empty)
        {
            strInfoTitle = "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，订单号为空！</h2>";
            return;
        }
        strOrderNo = order_no;
        using (msBsc.AppLogic.DataAlc.CBizShpChargeTradingLog objtradlog = new msBsc.AppLogic.DataAlc.CBizShpChargeTradingLog())
        {
            DataSet dsLog = objtradlog.DataObj.QueryBySQL("SELECT TRADING_SID='已支付',TRADING_NME,TRADING_QTY,TRADING_AMT,TRADING_TYPE_CID,CHARGE_SRC_CID='积分冲抵' FROM SHP_SCORE_TRADING_LOG A WHERE A.TRADING_TYPE_CID='消费' AND A.TRADING_NO='" + order_no + "' UNION SELECT TRADING_SID,TRADING_NME,TRADING_QTY=0,TRADING_AMT,TRADING_TYPE_CID,CHARGE_SRC_CID FROM SHP_CHARGE_TRADING_LOG A WHERE A.PAY_DIR='支出' AND A.TRADING_NO='" + order_no + "'");
            DataRow[] arrtem = dsLog.Tables[0].Select("TRADING_SID<>'已支付'");
            if (arrtem.Length > 0)
            {
                this.ExecJScript("$('#J_GoToEmailWeb').show();");
                this.ExecJScript("$('#J_GoToEmailWeb').attr('href','');");
                strInfoTitle = "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，应付金额<span style=\"color:#c50000;\">" + arrtem[0]["TRADING_AMT"].ToString() + "</span>元！</h2>";
            }
            else if(dsLog.Tables[0].Rows.Count>0)
            {
                strInfoTitle = "<i class=\"iconfont\"  >&#xf0156; </i> <h2 class=\"tsl\" >恭喜您、已成功支付订单！</h2>";
            }
            else
            {
                this.ExecJScript("$('#J_GoToEmailWeb').show();");
                this.ExecJScript("$('#J_GoToEmailWeb').attr('href','');");
                strInfoTitle = "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，订单信息未找到！</h2>";
            }
            if (arrtem.Length > 0 && strAlipayInfo != "OK" && strAlipayInfo != string.Empty)
            {
                strPayVali = "<p><span class=\"tsl\">本次支付校验：</span> <em></em><span class=\"tsl\">" + strAlipayInfo + "</span></p>";
            }
            for (int i = 0; i < dsLog.Tables[0].Rows.Count; i++)
            {
                if (i == 0)
                {
                    strOrderNme = dsLog.Tables[0].Rows[i]["TRADING_NME"].ToString();
                }
                strPaylist += "<p><span class=\"tsl\">" + dsLog.Tables[0].Rows[i]["CHARGE_SRC_CID"].ToString() + "：</span> <em></em><span class=\"tsl\" style=\"color:#c50000;\">" + dsLog.Tables[0].Rows[i]["TRADING_AMT"].ToString() + "</span>元！" + dsLog.Tables[0].Rows[i]["TRADING_SID"].ToString() + "</p>";
                //strPaylist += " <h2 class=\"tsl\" >" + dsLog.Tables[0].Rows[i]["CHARGE_SRC_CID"].ToString() + "支付：<span>" + arrtem[0]["TRADING_AMT"].ToString() + "</span></h2>";
            }
        }
    }

    //private void doSaveAlipay(string trade_no, string order_no, string total_fee, string subject, string body, string buyer_email, string trade_status, string refund_status)
    //{
    //    using (msBsc.AppLogic.DataAlc.CBizShpChargeTradingLog objtradlog = new AppLogic.DataAlc.CBizShpChargeTradingLog())
    //    {
    //        DataSet dsLog = this.DataObj.QueryBySQL("SELECT * FROM SHP_CHARGE_TRADING_LOG A WHERE A.TRADING_SID='待支付' AND A.PAY_DIR='支出' AND TRADING_NO IN ('" + strOrderNo.Replace(",", "','") + "')");
    //        dsLog.Tables[0].TableName = "SHP_CHARGE_TRADING_LOG";
    //    }
    //}




    /// <summary>
    /// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
    /// </summary>
    /// <returns>request回来的信息组成的数组</returns>
    public SortedDictionary<string, string> GetRequestGet()
    {
        int i = 0;
        SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
        NameValueCollection coll;
        //Load Form variables into NameValueCollection variable.
        coll = Request.QueryString;

        // Get names of all forms into a string array.
        String[] requestItem = coll.AllKeys;

        for (i = 0; i < requestItem.Length; i++)
        {
            sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
        }

        return sArray;
    }

    //private string strPayst = "0";
    //private string strPayType = "0";
    //private string strAmt = "0";
    //public string strOrderNo = "";
    //public string strOrderNme = "";
    //public string strErrInfo = "";
    //public string GetPayStat()
    //{
    //    if (strErrInfo != string.Empty)
    //    {
    //        return strErrInfo;
    //    }
    //    if (strPayst == "1")
    //    {
    //        if (strPayType == "0")
    //        {
    //            return "<i class=\"iconfont\"  >&#xf0156; </i> <h2 class=\"tsl\" >恭喜您、已成功支付积分<span style=\"color:#c50000;\">" + strAmt + "</span>分！</h2>";
    //        }
    //        else
    //        {
    //            return "<i class=\"iconfont\"  >&#xf0156; </i> <h2 class=\"tsl\" >恭喜您、已成功支付金额<span style=\"color:#c50000;\">" + strAmt + "</span>元！</h2>";
    //        }
    //    }
    //    else
    //    {
    //        this.ExecJScript("$('#J_GoToEmailWeb').show();");
    //        this.ExecJScript("$('#J_GoToEmailWeb').attr('href','');");
    //        if (strPayType == "0")
    //        {
    //            return "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，应付积分<span style=\"color:#c50000;\">" + strAmt + "</span>分！</h2>";
    //        }
    //        else
    //        {
    //            return "<i style=\"display: inline;float: left;margin-left: -40px;font-size: 32px;line-height: 32px;\"><img src=\"/Alipay/images/info_error_50.png\" alt=\"\" width=\"32px\" height=\"32px\"/></i> <h2 class=\"tsl\" >本次支付失败，应付金额<span style=\"color:#c50000;\">" + strAmt + "</span>元！</h2>";
    //        }
    //    }
    //}

    //private void ShowPayInfo()
    //{
    //    strOrderNo = this.Request.QueryString.Get("out_trade_no");
    //    if (!string.IsNullOrEmpty(strOrderNo))
    //    {
    //        using (msBsc.AppLogic.DataAlc.CBizShpOrderForm objorder = new msBsc.AppLogic.DataAlc.CBizShpOrderForm())
    //        {
    //            int iscore = 0;
    //            decimal decAmt = 0M;
    //            DataSet ds = objorder.SelectByNos(strOrderNo);
    //            string strOrdertm = "";
    //            string strRemarks = "";
    //            for(int i=0;i<ds.Tables[0].Rows.Count;i++)
    //            {
    //                if (ds.Tables[0].Rows[i]["PAYABLE_SCORE"].ToString() != "等待买家付款" || decimal.Parse(ds.Tables[0].Rows[i]["PAYABLE_AMT"].ToString() == string.Empty ? "0" : ds.Tables[0].Rows[i]["PAYABLE_AMT"].ToString())<=0)
    //                {
    //                    continue;
    //                }

    //                decAmt += decimal.Parse(ds.Tables[0].Rows[i]["PAYABLE_AMT"].ToString() == string.Empty ? "0" : ds.Tables[0].Rows[i]["PAYABLE_AMT"].ToString());
    //                strOrdertm += strOrdertm == string.Empty ? ds.Tables[0].Rows[i]["ORDER_FORM_NO"].ToString() : "," + ds.Tables[0].Rows[i]["ORDER_FORM_NO"].ToString();
    //                strOrderNme += strOrderNme == string.Empty ? ds.Tables[0].Rows[i]["ORDER_FORM_NME"].ToString() : "," + ds.Tables[0].Rows[i]["ORDER_FORM_NME"].ToString();
    //                strRemarks += strRemarks == string.Empty ? ds.Tables[0].Rows[i]["BUY_MEMO"].ToString() : "," + ds.Tables[0].Rows[i]["BUY_MEMO"].ToString();
    //            }


    //            if (decAmt > 0)
    //            {
    //                //支付类型
    //                string payment_type = "1";
    //                //必填，不能修改
    //                //服务器异步通知页面路径
    //                string notify_url = "http://localhost:808/Alipay/notify_url.aspx";
    //                //需http://格式的完整路径，不能加?id=123这类自定义参数        //页面跳转同步通知页面路径
    //                string return_url = "http://localhost:808/Alipay/return_url.aspx";
    //                //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/      
    //                //卖家支付宝帐户
    //                string seller_email = "@";
    //                //必填        //商户订单号
    //                string out_trade_no = strOrdertm;
    //                //商户网站订单系统中唯一订单号，必填        //订单名称
    //                string subject = strOrderNme;
    //                //必填        //付款金额
    //                string total_fee = decAmt.ToString();
    //                //必填        //订单描述     
    //                string body = strRemarks;
    //                //商品展示地址
    //                string show_url = "";
    //                //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html        //防钓鱼时间戳
    //                string anti_phishing_key = "";
    //                //若要使用请调用类文件submit中的query_timestamp函数        //客户端的IP地址
    //                string exter_invoke_ip = "";
    //                //非局域网的外网IP地址，如：221.0.0.1


    //                ////////////////////////////////////////////////////////////////////////////////////////////////

    //                //把请求参数打包成数组
    //                SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
    //                sParaTemp.Add("partner", Config.Partner);
    //                sParaTemp.Add("_input_charset", Config.Input_charset.ToLower());
    //                sParaTemp.Add("service", "create_direct_pay_by_user");
    //                sParaTemp.Add("payment_type", payment_type);
    //                sParaTemp.Add("notify_url", notify_url);
    //                sParaTemp.Add("return_url", return_url);
    //                sParaTemp.Add("seller_email", seller_email);
    //                sParaTemp.Add("out_trade_no", out_trade_no);
    //                sParaTemp.Add("subject", subject);
    //                sParaTemp.Add("total_fee", total_fee);
    //                sParaTemp.Add("body", body);
    //                sParaTemp.Add("show_url", show_url);
    //                sParaTemp.Add("anti_phishing_key", anti_phishing_key);
    //                sParaTemp.Add("exter_invoke_ip", exter_invoke_ip);

    //                //建立请求
    //                string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");
    //                Response.Write(sHtmlText);

    //            }



    //        }
    //    }
    //}


    //private void doPay()
    //{
    //    strOrderNo = this.Request.QueryString.Get("out_trade_no");
    //    if (!string.IsNullOrEmpty(strOrderNo))
    //    {
    //        using (msBsc.AppLogic.DataAlc.CBizShpOrderForm objorder = new msBsc.AppLogic.DataAlc.CBizShpOrderForm())
    //        {
    //            int iscore = 0;
    //            decimal decAmt = 0M;
    //            DataSet ds = objorder.SelectByNos(strOrderNo);
    //            strPayst = "0";
    //            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    //            {
    //                if (ds.Tables[0].Rows[i]["PAYABLE_SCORE"].ToString() == "等待买家付款")
    //                {
    //                    strPayst = "0";
    //                }
    //                else
    //                {
    //                    strPayst = "1";
    //                }
    //                iscore += int.Parse(ds.Tables[0].Rows[i]["PAYABLE_SCORE"].ToString() == string.Empty ? "0" : ds.Tables[0].Rows[i]["PAYABLE_SCORE"].ToString());
    //                decAmt += decimal.Parse(ds.Tables[0].Rows[i]["PAYABLE_AMT"].ToString() == string.Empty ? "0" : ds.Tables[0].Rows[i]["PAYABLE_AMT"].ToString());
    //                strOrderNme += strOrderNme == string.Empty ? ds.Tables[0].Rows[i]["ORDER_FORM_NME"].ToString() : "," + ds.Tables[0].Rows[i]["ORDER_FORM_NME"].ToString();
    //            }
    //            if (iscore > 0)
    //            {
    //                strPayType = "0";
    //                strAmt = iscore.ToString();
    //            }
    //            else
    //            {
    //                strPayType = "1";
    //                strAmt = decAmt.ToString();
    //            }



    //        }
    //    }
    //}

}
